package com.geniusk.common.utils;

import cn.hutool.core.lang.id.NanoId;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

/**
 * 设备工具类
 */
@Slf4j
@Configuration
public class DeviceUtil {

    /**
     * 获取设备密钥
     * @return 设备密钥
     */
    public static String getDeviceSecret(){
        return NanoId.randomNanoId(16);
    }

    /**
     * 生成设备密钥
     * @param content 加密前数据
     * @return 设备密钥
     */
    public static String encryptBase64(String content, String deviceKey){
        try{
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),
                    deviceKey.getBytes()).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            // 加密
            return aes.encryptBase64(content);
        }catch (Exception e){
            log.error(" 加密异常:{}",e.getMessage());
        }
        return null;
    }

    /**
     * 设备密钥解密
     * @param encryptString 设备密钥
     * @return 解密后数据
     */
    public static String decryptStr(String encryptString, String deviceKey){
        try{
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),
                    deviceKey.getBytes()).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            //解密
            return aes.decryptStr(encryptString);
        }catch (Exception e){
            log.error(" 解密异常:{}",e.getMessage());
        }
        return null;
    }

}
